//引入请求
import { reqCate, reqGoods } from "../../request/api"

//初始值
const initState = {
    //定义保存分类标题的数组
    cateTitle: [],
    //定义保存对于数据的数组
    cateGoods: [],
    //定义变量
    n:1,
}

//types

const types = {
    //分类标题
    CHANGE_CATETITLE: "CATE_CHANGE_CATETITLE",
    //分类数据
    CHANGE_CATEGOODS: "CATE_CHANGE_CATEGOODS",
    //修改n
    CHANGE_N: "CATE_CHANGE_N",
}


//修改数据
const  reducer =(state=initState,action)=>{
    switch(action.type){
        //分类标题
            case types.CHANGE_CATETITLE:
                return{
                    ...state,
                    cateTitle:action.arr
                }
            case types.CHANGE_CATEGOODS:
                return{
                    ...state,
                    cateGoods:action.arr
                }
            case types.CHANGE_N:
                return{
                    ...state,
                    n:action.n
                }
            default:
                    return state;              
    }
}
//组建派发的任务

export const actions={
        //修改分类标题
        changeCateTitle:(arr)=>({type:types.CHANGE_CATETITLE,arr}),
        //修改数据
        changeCateGoods:(arr)=>({type:types.CHANGE_CATEGOODS,arr}),
        //修改n
        changeN:(n)=>({type:types.CHANGE_N,n}),
        
        //标题请求
        reqCate: () => (dispatch, getState) => {
            reqCate().then(res => {
                if (res.data.code === 200) {
                    //修改
                    dispatch(actions.changeCateTitle(res.data.list))
                }
                // console.log(res);
            })
        },

        reqGoods:(id)=>(dispatch,getState)=>{
            dispatch(actions.changeN(id))
            let{n}=getState().list
            reqGoods({fid:n}).then(res=>{
                if(res.data.code===200){
                    let list =res.data.list?res.data.list:[]
                    dispatch(actions.changeCateGoods(list))
                }
            })
        }

}

//导出数据
export  const  getCateTitle =(state)=>state.list.cateTitle;
export const getN =state=>state.list.n; 
export const getCateGoods=state=>state.list.cateGoods;

//整体导出
export default reducer;